import wxService from '../common/wxService'
import tools from '../common/tools'
import { MlcEnum } from '../model/enum'
import * as wux from '../assets/components/wux';
import { ISubmitOrderResult } from '../model/order';
import { toast } from '../assets/components/wux'
import { config } from '../etc/config';
import { prompt } from '../assets/components/wux';

class utils {
    private timer: number = 2500;
    errorAlert;
    constructor() {
    }
    navigateTo(id?: string, type?: number, tag?: string) {
        let url;
        switch (type) {
            case MlcEnum.GoodsNavType.索引:
                url = tools.buildUrl('/pages/goods/list/index', { nid: id });
                break;
            case MlcEnum.GoodsNavType.商品:
                url = tools.buildUrl('/pages/goods/detail/index', { id: id });
                break;
            case MlcEnum.GoodsNavType.分类:
                url = tools.buildUrl('/pages/goods/list/index', { cid: id });
                break;
            case MlcEnum.GoodsNavType.品牌:
                url = tools.buildUrl('/pages/goods/list/index', { bid: id });
                break;
            case MlcEnum.GoodsNavType.标签:
                url = tools.buildUrl('/pages/goods/list/index', { label: id });
                break;
            case MlcEnum.GoodsNavType.固定:
                if (!tag) {
                    break;
                }
                if (tag.toLowerCase().indexOf('url') > -1) {
                    const content = tag.split('$');
                    url = tools.buildUrl('/pages/ad/index', { url: content[content.length - 1] });
                } else if (tag == "更多精品") {
                    url = '/pages/goods/list/index';
                }
                break;
        }
        if (url && url != '') {
            wxService.navigateTo(url, { 'id': id })
        }
    }

    showErrorToptips(error: { msg: string }) {
        const hideToptips = wux.toptips.show({
            timer: this.timer,
            text: error.msg || '请填写正确的字段',
            success: () => console.log('toptips', error)
        })
    }

    closeAllLoading() {
        setTimeout(function () {
            wx.hideLoading();
            wx.stopPullDownRefresh();
            wx.hideNavigationBarLoading();
        }, 1);
    }

    setBtnStatus(that) {
        that.setData({
            'btnDisabled': !that.data.btnDisabled,
            'btnLoading': !that.data.btnLoading,
        })
    }

    formatNumber(n: number): string {
        const formatString = n.toString();
        return formatString[1] ? formatString : '0' + formatString;
    }

    formatTime(date: Date, fmt?: string): string {
        if (fmt) {
            const o = {
                "M+": date.getMonth() + 1,
                "d+": date.getDate(),
                "h+": date.getHours(),
                "m+": date.getMinutes(),
                "s+": date.getSeconds(),
                "q+": Math.floor((date.getMonth() + 3) / 3),
                "S": date.getMilliseconds()
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();
        return [year, month, day].map(this.formatNumber).join('/') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
    }

    showToast(msg?: string) {
        toast.show({
            type: 'success',
            timer: this.timer,
            color: '#fff',
            text: msg || '操作成功',
        })
    }

    showToastCancel(msg?: string) {
        toast.show({
            type: 'cancel',
            timer: this.timer,
            color: '#fff',
            text: msg,
        })
    }

    showToastErr(msg?: string) {
        toast.show({
            type: 'warn',
            timer: this.timer,
            color: '#fff',
            text: msg,
        })
    }

    showToastText(msg?: string) {
        toast.show({
            type: 'text',
            timer: this.timer,
            color: '#fff',
            text: msg,
        })
    }

    thum(orign: string, size: number | string) {
        if (/^\//.test(orign)) {
            orign = config.host + orign;
        }
        if (!size) {
            return orign;
        }
        const extension = new RegExp('\\.[^/]+$').exec(orign);
        if (extension) {
            orign = orign.replace(new RegExp('\\.[^/]+$'), `_${size}` + extension[0]);
        } else {
            orign = `${orign}_${size}.jpg`;
        }
        return orign;
    }

    loadError(fun) {
        let options = {
            title: '',
            text: '加载失败!',
            icon: 'http://r.59im.com/wx/tips/lack_network_anomaly_icon@2x.png',
            buttons: [
                {
                    text: '重新加载'
                }
            ],
            buttonClicked: (index, item) => {
                if (fun && typeof fun == 'function') {
                    if (this.errorAlert) {
                        this.errorAlert.hide();
                    }
                    setTimeout(() => {
                        fun();
                    }, 400);
                }
            }
        };
        this.errorAlert = prompt.init('msg1', options);
        this.errorAlert.show();
    }
}

export default new utils()

